package servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import dto.ResultDto;
import entity.PowerBattery;
import service.PowerBatteryService;
import service.impl.PowerBatteryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/Update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter out = resp.getWriter();
                StringBuilder json = new StringBuilder();
                String line = null;
                try {
                    BufferedReader reader = req.getReader();
                    while ((line = reader.readLine()) != null) {
                        json.append(line);
                    }
                } catch (IOException e) { /* handle exception */ }

                // 解析JSON字符串为Java对象或其他处理方式
                JSONObject jsonObject = JSON.parseObject(json.toString());
        PowerBatteryService powerBatteryService=new PowerBatteryServiceImpl();
        int i = powerBatteryService.updatePowerBattery(jsonObject.toJavaObject(PowerBattery.class));
        ResultDto resultDto=new ResultDto();
        if (i>0){
            resultDto.setStatus(1);
            resultDto.setMessage("修改成功！");
        }else {
            resultDto.setStatus(0);
            resultDto.setMessage("修改失败！");
        }
        out.print(JSON.toJSONString(resultDto));
        out.flush();
        out.close();
    }
}
